package cn.z2huo.demo.spring.webmvc.controller.async;

import cn.hutool.core.thread.ThreadUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.async.DeferredResult;

import java.util.concurrent.Callable;
import java.util.concurrent.TimeUnit;

/**
 * <p>Spring MVC 异步请求接口
 *
 * @author z2huo
 */
@RestController
@RequestMapping("/async")
@RequiredArgsConstructor
public class AsyncController {

    private final ThreadPoolTaskExecutor executor;

    @GetMapping("/callable")
    public Callable<String> stringCallableTest() {
        return () -> {
            ThreadUtil.sleep( 10, TimeUnit.SECONDS);
            return "hello world";
        };
    }

    @GetMapping("/deferredResult")
    public DeferredResult<String> stringDeferredResultTest() {
        DeferredResult<String> deferredResult = new DeferredResult<>();

        executor.execute(() -> {
            ThreadUtil.sleep( 10, TimeUnit.SECONDS);
            deferredResult.setResult("hello world 2");
        });
        return deferredResult;
    }

}
